<?php
header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );  // disable IE caching
header( "Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . " GMT" ); 
header( "Cache-Control: no-cache, must-revalidate" ); 
header( "Pragma: no-cache" );
header( "Content-type: application/json");
$from=0;
$to=0;
$grp=1;
function dataFormat($ts, $value) {
    return array($ts,$value);
}
$js=array();
$xmlOut=simplexml_load_string("<?xml version=\"1.0\" encoding=\"utf-8\"?><rtdata/>");
$db = new PDO('sqlite:/var/www/xml/sensor.sqlite');
$db->setAttribute(PDO::ATTR_TIMEOUT, 5);
//$id=$db->quote($_GET["grid"]);
$id=1;
if (isset($_GET["from"])) $from=$db->quote($_GET["from"]);
if (isset($_GET["to"])) $to=$db->quote($_GET["to"]);
if (isset($_GET["grp"])) $grp=$db->quote($_GET["grp"]);
//calcola vincolo su ts
if ($from!=0 && $to!=0)
	$vv=" ts>=$from AND ts<=$to ";
else
	$vv = " 1 ";
//identifica gli assi interessati
$n=1;
$result = $db->query("SELECT DISTINCT chConf.type FROM tracklist JOIN chConf on chConf.sensor=tracklist.sensor and chConf.channel=tracklist.channel WHERE graphid=$id");
$axs=array();
foreach($result as $row){
$axs[$row["type"]]=$n++;
}


$result = $db->query("SELECT tracklist.color,tracklist.sensor, tracklist.channel,sensors.name,chConf.label,chConf.type,units.unit,units.aggregate from tracklist JOIN sensors on sensors.sensor=tracklist.sensor JOIN chConf on chConf.sensor=tracklist.sensor and chConf.channel=tracklist.channel JOIN units on chconf.type=units.type where graphid=$id ORDER BY tracklist.sensor,tracklist.channel ASC");
foreach($result as $row){
$p=array();
if ($row["name"]=="")
	$name=$row["sensor"];
else
	$name=$row["name"];
if ($row["label"]=="")
	$label=$row["channel"];
else
	$label=$row["label"];
$p['label']=$name.".".$label."[".$row["unit"]."]";
$p["color"]=$row["color"];
$p["yaxis"]=$axs[$row["type"]];
$result1 = $db->query("SELECT 1000*120*round(ts/120) ts,(".$row["aggregate"]."(value)) FROM meas where sensor=".$row["sensor"]." AND channel=". $row["channel"]. " AND $vv GROUP BY 1000*120*round(ts/120) ORDER BY ts ASC");
$data = $result1->fetchAll(PDO::FETCH_FUNC, "dataFormat");
$p['data']=$data;
$js[]=$p;
}
echo json_encode($js);
$db = NULL;
?>


